package repository

import (
	"context"
	"fmt"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
	"time"
)

type deptRepository struct{}

func (r deptRepository) Create(u *model.Dept) error {
	return db.GetDB().Create(&u).Error
}
func (r deptRepository) FindById(deptId int64) (u *model.Dept, err error) {
	err = db.GetDB().Where("dept_id = ? ", deptId).Find(&u).Error
	return
}
func (r deptRepository) UpdateById(u *model.Dept) (err error) {
	return db.GetDB().Save(&u).Error
}
func (r deptRepository) FindAll(name string) (li []*model.Dept, err error) {
	err = db.GetDB().Model(&model.Dept{}).
		Where("dept_name like ? ", "%"+name+"%").Find(&li).Error
	return
}

/////////////////////

func (r deptRepository) DeleteById(deptId int64) (err error) {
	return db.GetDB().Model(&model.Dept{}).Where("dept_id = ?", deptId).Update("deleted_at", time.Now().Unix()).Error
}

func (r deptRepository) UpdateUserDeptId(userIds []int64, deptId int64) (err error) {
	err = db.GetDB().Exec("UPDATE sys_user_extend set dept_id =? where user_id in ?", deptId, userIds).Error
	return
}

func (r deptRepository) DeleteMapTeamForAPP(c context.Context, teamId int64) (err error) {
	err = db.GetDB().Exec("delete from sys_map_app_dept where dept_id = ? ", teamId).Error
	return
}

func (r deptRepository) InsertMapTeamFormUser(teamId int64, userIds []int64) (err error) {
	sqlStr := "insert  into sys_map_user_dept (user_id, dept_id) values "
	for i := range userIds {
		sqlStr += fmt.Sprintf("(%d,%d),", userIds[i], teamId)
	}
	sqlStr = sqlStr[:len(sqlStr)-1]
	return db.GetDB().Exec(sqlStr).Error
}

func (r deptRepository) FindTeamMapAppIds(teamId int64) (appIds []int64, err error) {
	err = db.GetDB().Raw("select  app_id from sys_map_app_dept where dept_id = ? ", teamId).Scan(&appIds).Error
	return
}

func (r deptRepository) SelectDeptByUserId(userId int64) (dept model.Dept, err error) {
	err = db.GetDB().Raw("SELECT * FROM sys_dept WHERE dept_id in (select dept_id from sys_user_extend where user_id =?)", userId).Find(&dept).Error
	return
}
